package com.roubsite.admin.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import com.roubsite.admin.bean.RsOauthSystem;
import com.roubsite.admin.dao.rsOauthSystem.RsOauthSystemDao;
import com.roubsite.admin.dao.rsOauthSystem.IRsOauthSystemDao;

import com.roubsite.database.bean.Record;
import com.roubsite.utils.JsonUtils;
import com.roubsite.utils.StringUtils;
import com.roubsite.utils.UuidUtils;
import com.roubsite.web.action.RSAction;
import com.roubsite.database.dao.DataSet;
import com.roubsite.database.annotation.Dao;

@SuppressWarnings("rawtypes")
public class RsOauthSystemAction extends RSAction {
	@Dao(dataSource = "dataSource", impl = RsOauthSystemDao.class)
	IRsOauthSystemDao rsOauthSystemDao;

	@Override
	public void execute() throws Exception {

		this.display("/rsOauthSystem/listRsOauthSystem.html");
	}

	public void doQuery() throws IOException {
		Record record = new Record();
		Map paramSet = (Map) this.getParamSet(false);
		record.fromBeanMap((Map) paramSet.get("__data__"));
		DataSet ret = rsOauthSystemDao.queryd(record, (int) paramSet.get("__offset__"),
				(int) paramSet.get("__limit__"));
		this.print(JsonUtils.convertToString(ret));
	}

	public void doDel() throws Exception {
		String jsonString = (String) this.getParamSet(true);
		List ids = JsonUtils.readToObject(jsonString, ArrayList.class);
		int r = rsOauthSystemDao.del(ids);
		Map ret = new HashMap();
		ret.put("status", r);
		this.print(JsonUtils.convertToString(ret));
	}

	public void doEdit() throws ServletException, IOException {
		String editState = this.g("editState");
		String method = this.g("method");
		if (StringUtils.isEmpty(editState)) {
			// 正常打开页面
			if ("UPDATE".equals(method)) {
				String id = this.g("id");
				DataSet ret = rsOauthSystemDao.getInfoById(id);
				this.assign("retInfo", JsonUtils.convertToString(ret));
			}
			this.assign("method", method);
			this.display("/rsOauthSystem/editRsOauthSystem.html");
			return;
		}
		// 有数据提交
		String paramSet = (String) this.getParamSet(true);
		Record r = new Record();
		r.setState(Integer.parseInt(editState));
		r.fromJson(paramSet);

		if (!StringUtils.isNotEmptyObject(r.get("OAUTH_SYSTEM_ID"))) {
			r.set("OAUTH_SYSTEM_ID", UuidUtils.getUuid());
			r.set("OAUTH_SYSTEM_SECRET",
					StringUtils.md5(UuidUtils.getUuid() + "RoubSiteSystemSecert" + UuidUtils.getUuid()));
		}

		int status = rsOauthSystemDao.saveData(r, RsOauthSystem.class);
		Map ret = new HashMap();
		ret.put("status", status);
		this.print(JsonUtils.convertToString(ret));

	}
}
